var express = require('express');
var router = express.Router();
const { Chat } = require('../db/user')
const path = require('path')
const multer = require('multer')

// 配置 multer 将文件保存到 uploads 目录
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, '..', 'uploads'))
  },
  filename: function (req, file, cb) {
    // 优先使用客户端传入的扩展名，其次根据 mimetype 推断
    let extFromClient = (req.body && typeof req.body.ext === 'string' && req.body.ext.trim()) ? req.body.ext.trim() : ''
    if (extFromClient && !extFromClient.startsWith('.')) extFromClient = '.' + extFromClient
    let extFromMimetype = ''
    if (file && file.mimetype) {
      if (file.mimetype === 'audio/aac' || file.mimetype === 'audio/x-aac') extFromMimetype = '.aac'
      else if (file.mimetype === 'audio/mpeg') extFromMimetype = '.mp3'
      else if (file.mimetype === 'audio/mp4') extFromMimetype = '.m4a'
      else if (file.mimetype === 'audio/wav') extFromMimetype = '.wav'
      else if (file.mimetype === 'audio/amr') extFromMimetype = '.amr'
      else if (file.mimetype === 'image/jpeg') extFromMimetype = '.jpg'
      else if (file.mimetype === 'image/png') extFromMimetype = '.png'
      else if (file.mimetype === 'image/gif') extFromMimetype = '.gif'
      else if (file.mimetype === 'image/webp') extFromMimetype = '.webp'
    }
    const ext = extFromClient || extFromMimetype || (path.extname(file.originalname || '') || '')
    // 根据类型决定前缀
    const isImage = (file && file.mimetype && file.mimetype.startsWith('image/'))
    const isAudio = (file && file.mimetype && file.mimetype.startsWith('audio/'))
    const prefix = isImage ? 'image_' : isAudio ? 'voice_' : 'file_'
    const fname = prefix + Date.now() + '_' + Math.floor(Math.random() * 1e9) + (ext || (isAudio ? '.aac' : isImage ? '.jpg' : ''))
    cb(null, fname)
  }
})
const upload = multer({ storage })

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

// 获取当前用户的会话列表
router.get('/chats', async function(req, res) {
  try {
    const userId = req.query.userId
    if (!userId) return res.status(400).json({ error: '缺少 userId' })
    const chats = await Chat.find({ participants: userId })
      .populate('participants', '_id username avatar')
      .sort({ updatedAt: -1 })
      .lean()
    res.json(chats)
  } catch (e) {
    res.status(500).json({ error: e.message })
  }
});

// 创建或获取两人会话
router.post('/chats/open', async function(req, res) {
  try {
    const { a, b } = req.body
    if (!a || !b) return res.status(400).json({ error: '缺少用户参数' })
    let chat = await Chat.findOne({ participants: { $all: [a, b], $size: 2 } })
    if (!chat) {
      chat = await Chat.create({ participants: [a, b], messages: [] })
    }
    res.json({ _id: chat._id })
  } catch (e) {
    res.status(500).json({ error: e.message })
  }
});

// 创建或获取与医院/医生的会话
router.post('/chats/openOrCreate', async function(req, res) {
  try {
    const { fromUserId, targetType, targetId, targetName } = req.body
    
    console.log('创建会话请求参数:', { fromUserId, targetType, targetId, targetName })
    
    if (!fromUserId || !targetType || !targetId) {
      console.error('缺少必要参数:', { fromUserId, targetType, targetId })
      return res.status(400).json({ error: '缺少必要参数' })
    }
    
    // 为医院/医生创建虚拟用户ID（基于targetType和targetId）
    const virtualUserId = `${targetType}_${targetId}`
    console.log('虚拟用户ID:', virtualUserId)
    
    // 查找或创建会话
    let chat = await Chat.findOne({ 
      participants: { $all: [fromUserId, virtualUserId], $size: 2 } 
    })
    
    console.log('查找现有会话结果:', chat ? '找到' : '未找到')
    
    if (!chat) {
      console.log('创建新会话...')
      // 创建新会话
      chat = await Chat.create({ 
        participants: [fromUserId, virtualUserId], 
        messages: [],
        // 存储目标信息用于显示
        targetInfo: {
          type: targetType,
          id: targetId,
          name: targetName
        }
      })
      console.log('新会话创建成功:', chat._id)
    }
    
    const response = { 
      _id: chat._id,
      participants: chat.participants,
      targetInfo: chat.targetInfo
    }
    
    console.log('返回会话信息:', response)
    res.json(response)
  } catch (e) {
    console.error('创建会话失败:', e)
    res.status(500).json({ error: e.message })
  }
});

// 获取会话消息
router.get('/chats/:chatId/messages', async function(req, res) {
  try {
    const { chatId } = req.params
    const chat = await Chat.findById(chatId).lean()
    if (!chat) return res.status(404).json({ error: '会话不存在' })
    res.json(chat.messages || [])
  } catch (e) {
    res.status(500).json({ error: e.message })
  }
});

// 发送消息
router.post('/chats/:chatId/messages', async function(req, res) {
  try {
    const { chatId } = req.params
    const { senderId, content, type, voiceUrl, voiceDuration, imageUrl, imageWidth, imageHeight } = req.body
    if (!senderId) return res.status(400).json({ error: '缺少 senderId' })
    // 判断类型并校验必要字段
    const isVoice = type === 'voice'
    const isImage = type === 'image'
    if (!isVoice && !isImage && !content) return res.status(400).json({ error: '缺少 content' })
    if (isVoice && !voiceUrl) return res.status(400).json({ error: '缺少 voiceUrl' })
    if (isImage && !imageUrl) return res.status(400).json({ error: '缺少 imageUrl' })
    const chat = await Chat.findById(chatId)
    if (!chat) return res.status(404).json({ error: '会话不存在' })
    const msg = {
      senderId,
      content: isVoice ? '[语音消息]' : isImage ? '[图片]' : content,
      type: isVoice ? 'voice' : isImage ? 'image' : 'text',
      voiceUrl: isVoice ? voiceUrl : undefined,
      voiceDuration: isVoice ? Number(voiceDuration) || 0 : undefined,
      imageUrl: isImage ? imageUrl : undefined,
      imageWidth: isImage ? (Number(imageWidth) || undefined) : undefined,
      imageHeight: isImage ? (Number(imageHeight) || undefined) : undefined,
      createdAt: new Date(),
      readBy: [senderId]
    }
    chat.messages.push(msg)
    chat.updatedAt = new Date()
    await chat.save()
    // 返回刚保存的包含 _id 的子文档
    const saved = chat.messages[chat.messages.length - 1]
    try {
      const io = req.app.get('io')
      if (io) {
        io.to('chat:' + String(chatId)).emit('chat:newMessage', { chatId: String(chatId), message: saved })
      }
    } catch (_) {}
    res.json(saved)
  } catch (e) {
    res.status(500).json({ error: e.message })
  }
});

// 获取未读汇总（按对方分组）
router.get('/messages/unreadSummary', async function(req, res) {
  try {
    const { userId } = req.query
    if (!userId) return res.status(400).json({ error: '缺少 userId' })
    const chats = await Chat.find({ participants: userId }).lean()
    const map = {}
    chats.forEach((c) => {
      (c.messages || []).forEach((m) => {
        const isUnread = !(m.readBy || []).some((x) => String(x) === String(userId))
        if (isUnread) {
          const otherId = String((c.participants || []).find((p) => String(p) !== String(userId)))
          if (!map[otherId]) map[otherId] = { count: 0, lastTime: 0 }
          map[otherId].count += 1
          map[otherId].lastTime = Math.max(map[otherId].lastTime, new Date(m.createdAt).getTime())
        }
      })
    })
    res.json(map)
  } catch (e) {
    res.status(500).json({ error: e.message })
  }
});

// 文件上传：返回可直接访问的 URL（/uploads/xxx）
router.post('/upload', upload.single('file'), async function(req, res) {
  try {
    if (!req.file) return res.status(400).json({ error: '未接收到文件' })
    // 基于当前请求构造可访问的绝对 URL（小程序播放建议使用 HTTPS）
    const protocol = (req.headers['x-forwarded-proto'] || req.protocol || 'http')
    const host = req.headers['x-forwarded-host'] || req.headers.host
    const base = `${protocol}://${host}`
    const url = `${base}/uploads/${req.file.filename}`
    res.json({ url, filename: req.file.filename })
  } catch (e) {
    res.status(500).json({ error: e.message })
  }
})


// 获取语音文件信息接口
router.get('/voice/info/:filename', async function(req, res) {
  try {
    const { filename } = req.params
    const filePath = path.join(__dirname, '..', 'uploads', filename)
    
    // 检查文件是否存在
    const fs = require('fs')
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({ error: '语音文件不存在' })
    }
    
    // 获取文件信息
    const stats = fs.statSync(filePath)
    const fileUrl = `/uploads/${filename}`
    
    res.json({
      filename,
      url: fileUrl,
      size: stats.size,
      createdAt: stats.birthtime,
      modifiedAt: stats.mtime,
      exists: true
    })
  } catch (e) {
    console.error('获取语音文件信息失败:', e)
    res.status(500).json({ error: '获取语音文件信息失败: ' + e.message })
  }
})

// 删除语音文件接口
router.delete('/voice/:filename', async function(req, res) {
  try {
    const { filename } = req.params
    const filePath = path.join(__dirname, '..', 'uploads', filename)
    
    // 检查文件是否存在
    const fs = require('fs')
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({ error: '语音文件不存在' })
    }
    
    // 删除文件
    fs.unlinkSync(filePath)
    
    res.json({ 
      message: '语音文件删除成功',
      filename,
      deleted: true
    })
  } catch (e) {
    console.error('删除语音文件失败:', e)
    res.status(500).json({ error: '删除语音文件失败: ' + e.message })
  }
})

// 将某会话消息设为已读
router.post('/chats/:chatId/readAll', async function(req, res) {
  try {
    const { chatId } = req.params
    const { userId } = req.body
    if (!userId) return res.status(400).json({ error: '缺少 userId' })
    const chat = await Chat.findById(chatId)
    if (!chat) return res.status(404).json({ error: '会话不存在' })
    chat.messages.forEach((m) => {
      const has = (m.readBy || []).some((x) => String(x) === String(userId))
      if (!has) m.readBy = [...(m.readBy || []), userId]
    })
    await chat.save()
    try {
      const io = req.app.get('io')
      if (io) io.to('chat:' + String(chatId)).emit('chat:readAll', { chatId: String(chatId), userId: String(userId) })
    } catch (_) {}
    res.json({ ok: true })
  } catch (e) {
    res.status(500).json({ error: e.message })
  }
});

// 健康检查接口
router.get('/api/health', function(req, res, next) {
  res.json({ 
    status: 'ok', 
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    message: 'Server is running',
    version: '1.0.0'
  });
});

module.exports = router;
